﻿using FineUIPro;
using MyDataProcess;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace KPI_SYSTEM.Code
{
    public static class PublicMethod
    {
        public static String approvalMenuName = "";
        public static String approvalPageName = "";
        public static String approvalID = "";
        /// <summary>
        /// 新浪api
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string GetCS(string ip)
        {
            try
            {
                string url = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip + "&json=true";
                Encoding encoding = Encoding.GetEncoding("GB2312");
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "application/json;charset=unicode";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                String result = "";
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    result =  reader.ReadToEnd();
                    JObject reaultJson = JObject.Parse(result);
                    return reaultJson["addr"].ToString();
                }
            }
            catch
            {
                return "未知";
            }

        }
        public static string GetUserIp()
        {
            string ip;
            string[] temp;
            bool isErr = false;
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            else
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
            }
            if (ip.Length > 15)
            {
                isErr = true;
            }
            else
            {
                temp = ip.Split('.');
                if (temp.Length == 4)
                {
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (temp[i].Length > 3) isErr = true;
                    }
                }
                else
                    isErr = true;
            }
            if (isErr)
            {
                return "1.1.1.1";
            }
            else
            {
                return ip;
            }
        }

        /// <summary>
        /// 在指定的字符串列表CnStr中检索符合拼音索引字符串
        /// </summary>
        /// <param name="CnStr">汉字字符串</param>
        /// <returns>相对应的汉语拼音首字母串</returns>
        public static string GetSpellCode(string CnStr)
        {

            string strTemp = "";
            int iLen = CnStr.Length;
            int i = 0;
            for (i = 0; i <= iLen - 1; i++)
            {
                strTemp += GetCharSpellCode(CnStr.Substring(i, 1));
            }
            return strTemp;
        }
        public static string EncodeBase64(string code_type, string code)
        {
            string encode = "";
            byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = code;
            }
            return encode;
        }
        public static string GetMD5Hash(string str)
        {
            //就是比string往后一直加要好的优化容器
            StringBuilder sb = new StringBuilder();
            using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
            {
                //将输入字符串转换为字节数组并计算哈希。
                byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(str));

                //X为     十六进制 X都是大写 x都为小写
                //2为 每次都是两位数
                //假设有两个数10和26，正常情况十六进制显示0xA、0x1A，这样看起来不整齐，为了好看，可以指定"X2"，这样显示出来就是：0x0A、0x1A。 
                //遍历哈希数据的每个字节
                //并将每个字符串格式化为十六进制字符串。
                int length = data.Length;
                for (int i = 0; i < length; i++)
                    sb.Append(data[i].ToString("X2"));

            }
            return sb.ToString();
        }
        /// <summary>
        /// 得到一个汉字的拼音第一个字母，如果是一个英文字母则直接返回大写字母
        /// </summary>
        /// <param name="CnChar">单个汉字</param>
        /// <returns>单个大写字母</returns>
        private static string GetCharSpellCode(string CnChar)
        {
            long iCnChar;
            byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar);
            //如果是字母，则直接返回
            if (ZW.Length == 1)
            {
                return CnChar.ToUpper();
            }

            else
            {
                // get the array of byte from the single char
                int i1 = (short)(ZW[0]);
                int i2 = (short)(ZW[1]);
                iCnChar = i1 * 256 + i2;
            } 
            // iCnChar match the constant
            if ((iCnChar >= 45217) && (iCnChar <= 45252))
            {
                return "A";
            }
            else if ((iCnChar >= 45253) && (iCnChar <= 45760))
            {

                return "B";

            }
            else if ((iCnChar >= 45761) && (iCnChar <= 46317))
            {

                return "C";

            }
            else if ((iCnChar >= 46318) && (iCnChar <= 46825))
            {

                return "D";

            }
            else if ((iCnChar >= 46826) && (iCnChar <= 47009))
            {

                return "E";

            }
            else if ((iCnChar >= 47010) && (iCnChar <= 47296))
            {

                return "F";

            }
            else if ((iCnChar >= 47297) && (iCnChar <= 47613))
            {

                return "G";

            }
            else if ((iCnChar >= 47614) && (iCnChar <= 48118))
            {

                return "H";

            }
            else if ((iCnChar >= 48119) && (iCnChar <= 49061))
            {

                return "J";

            }
            else if ((iCnChar >= 49062) && (iCnChar <= 49323))
            {

                return "K";

            }
            else if ((iCnChar >= 49324) && (iCnChar <= 49895))
            {

                return "L";

            }
            else if ((iCnChar >= 49896) && (iCnChar <= 50370))
            {

                return "M";

            }
            else if ((iCnChar >= 50371) && (iCnChar <= 50613))
            {

                return "N";

            }
            else if ((iCnChar >= 50614) && (iCnChar <= 50621))
            {

                return "O";

            }
            else if ((iCnChar >= 50622) && (iCnChar <= 50905))
            {

                return "P";

            }
            else if ((iCnChar >= 50906) && (iCnChar <= 51386))
            {

                return "Q";

            }
            else if ((iCnChar >= 51387) && (iCnChar <= 51445))
            {

                return "R";

            }
            else if ((iCnChar >= 51446) && (iCnChar <= 52217))
            {

                return "S";

            }
            else if ((iCnChar >= 52218) && (iCnChar <= 52697))
            {

                return "T";

            }
            else if ((iCnChar >= 52698) && (iCnChar <= 52979))
            {

                return "W";

            }
            else if ((iCnChar >= 52980) && (iCnChar <= 53640))
            {

                return "X";

            }
            else if ((iCnChar >= 53689) && (iCnChar <= 54480))
            {

                return "Y";

            }
            else if ((iCnChar >= 54481) && (iCnChar <= 55289))
            {

                return "Z";

            }
            else

                return ("?");

        }


        public static void AlertMessage(String alertMessage, String title)
        {
            Alert alert = new Alert();
            alert.Message = alertMessage;
            alert.Title = title;
            alert.MessageBoxIcon = (MessageBoxIcon)Enum.Parse(typeof(MessageBoxIcon), "Warning", true);
            alert.Target = (Target)Enum.Parse(typeof(Target), "Self", true);
            alert.Show();
        }
        public static HSSFWorkbook NPOIExcel(Grid grid)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");

            NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);
            sheet.DefaultColumnWidth = 15;
            ICellStyle style = book.CreateCellStyle();
            IFont font = book.CreateFont();
            font.FontHeightInPoints = 12;
            style.Alignment = HorizontalAlignment.Center;
            style.VerticalAlignment = VerticalAlignment.Center;

            style.SetFont(font);

            for (int i = 0; i < grid.Columns.Count; i++)
            {

                if (grid.Columns[i].Hidden != true && grid.Columns[i].HeaderText != "")
                {
                    ICell cell = headerrow.CreateCell(i);
                    cell.CellStyle = style;
                    cell.SetCellValue(grid.Columns[i].HeaderText);
                }
            }
            if (grid.Rows.Count > 0)
            {
                for (int i = 0; i < grid.Rows.Count; i++)
                {
                    headerrow = sheet.CreateRow(i + 1);
                    for (int j = 0; j < grid.Columns.Count; j++)
                    {
                        if (grid.Columns[j].Hidden != true && grid.Columns[j].HeaderText != "")
                        {
                            string html = grid.Rows[i].Values[j].ToString();
                            if (!html.StartsWith(Grid.TEMPLATE_PLACEHOLDER_PREFIX))
                            {
                                headerrow.CreateCell(j).SetCellValue(grid.Rows[i].Values[j].ToString());
                            }
                        }

                    }
                }
            }
            return book;
        }
        public static void InsertByDataTable(DataTable table,String tableName)
        {
            StringBuilder sqlInsert = new StringBuilder();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                StringBuilder sqlColumn = new StringBuilder();
                StringBuilder sqlValue = new StringBuilder();
                foreach (DataColumn item in table.Columns)
                {
                    sqlColumn.Append(item.ColumnName + ",");
                    if (table.Rows[i][item.ColumnName].ToString() != "")
                    {
                        sqlValue.Append("'" + table.Rows[i][item.ColumnName].ToString() + "',");
                    }
                    else
                    {
                        sqlValue.Append("NULL,");
                    }
                }
                sqlInsert.Append("INSERT INTO " + tableName + "("+ sqlColumn.ToString().TrimEnd(',')+") VALUES("+ sqlValue.ToString().TrimEnd(',') + ");");
            }
            SqlHelper.ExecuteNonQuery(CommandType.Text, sqlInsert.ToString());
        }
        public static string GetRenderedHtmlSource(Control ctrl)
        {
            if (ctrl != null)
            {
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        ctrl.RenderControl(htw);

                        return sw.ToString();
                    }
                }
            }
            return String.Empty;
        }
        public static void SetDataMethod(String sql, String type, Dictionary<String, String> keyValues)
        {
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQL_Server"].ConnectionString);
            DataProcess dp1 = new DataProcess();
            DataSet ds1 = new DataSet();//创建dataset
            SqlDataAdapter dataAdapter = new SqlDataAdapter(sql, conn);//创建dataadapter
            SqlCommandBuilder cb = new SqlCommandBuilder(dataAdapter);//使用oraclecommand类和dataadapter类对数据库操作
            dataAdapter.Fill(ds1, "serverInfo");
            DataTable table = ds1.Tables[0];
            if (type == "Add")
            {
                DataRow dataRow = table.NewRow();
                foreach (var item in keyValues)
                {
                    dataRow[item.Key] = item.Value;
                }
                table.Rows.Add(dataRow);
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
            }
            if (type == "Update")
            {
                DataRow dataRow = table.Rows[0];
                foreach (var item in keyValues)
                {
                    dataRow[item.Key] = item.Value;
                }
                dataAdapter.Update(table.GetChanges());
                table.AcceptChanges();
            }
        }
        public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }
        public static void GetApprovalButton(String pageName, Toolbar toolbar,Grid grid)
        {
            DataTable approvalMappings = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT REC_ID,APPROVAL_MAPPING FROM HOS_APPROVAL_MAIN").Tables[0];
            DataTable pageMessage = SqlHelper.ExecuteDataset(CommandType.Text, "SELECT TOP 1 * FROM MENU_DICT WHERE CODE_PATH LIKE '%" + pageName + "%'").Tables[0];
            if (approvalMappings != null && approvalMappings.Rows.Count > 0  )
            {
                for (int i = 0; i < approvalMappings.Rows.Count; i++)
                {
                    String mappingIDs = "," + approvalMappings.Rows[i]["APPROVAL_MAPPING"].ToString() + ",";
                    if (pageMessage != null && pageMessage.Rows.Count > 0)
                    {
                        if (mappingIDs.Contains("," + pageMessage.Rows[0]["REC_ID"].ToString() + ","))
                        {
                            approvalMenuName = pageMessage.Rows[0]["MENU_NAME"].ToString();
                            approvalPageName = pageName;
                            approvalID = approvalMappings.Rows[i]["REC_ID"].ToString();
                            FineUIPro.Button btn = new Button();
                            btn.Text = "提交审核";
                            btn.DisableControlBeforePostBack = false;
                            btn.OnClientClick = "SubapprovalButtonFun("+ grid.ClientID + ",'"+ approvalMenuName + "','"+ approvalPageName + "','"+ approvalID + "')";
                            toolbar.Items.Add(btn);
                            HiddenField hiFieldPageName = new HiddenField();
                            hiFieldPageName.ID = "hiFieldPageName";
                            hiFieldPageName.Text = pageName;
                            toolbar.Items.Add(hiFieldPageName);
                            HiddenField hiFieldapprovalID = new HiddenField();
                            hiFieldapprovalID.ID = "hiFieldapprovalID";
                            hiFieldapprovalID.Text = approvalID;
                            toolbar.Items.Add(hiFieldapprovalID);


                        }
                    }
                }
            }
           
        }
       

    }
    public partial class PatientInfoModel
    {

        public string PATIENT_NUMBER { get; set; }
        public string PATIENT_NAME { get; set; }
        public string PATIENT_SEX_NAME { get; set; }
        public string PATIENT_AGE { get; set; }
        public string BL_NAME { get; set; }
        public string RECIVE_TIME { get; set; }
        public string OUT_TIME { get; set; }
        public string OUT_TYPE_NAME { get; set; }
        public string SITE_NAME { get; set; }
        public string PATIENT_PHONE { get; set; }
        public string PATIENT_STREET { get; set; }
        public string OUT_REMARK { get; set; }
        public int REC_ID { get; set; }
        public int PATIENT_STATUS { get; set; }
        public string FIRST_EXPOSE_TIME { get; set; }
        public string SURPLUS_TIME { get; set; }
        public string FIRST_TEST_TIME { get; set; }
        public string FIRST_TEST_RESULT_NAME { get; set; }
        public string SECOND_TEST_TIME { get; set; }
        public string SECOND_TEST_RESULT_NAME { get; set; }
        public string PATIENT_REMARK { get; set; }
        public string OUT_PLACE_NAME { get; set; }
    }
    public partial class PATIENT_SITE_CARD
    {

        public string PATIENT_NUMBER { get; set; }
        public string PATIENT_NAME { get; set; }
        public string PATIENT_SEX_NAME { get; set; }
        public string PATIENT_AGE { get; set; }
        public string PATIENT_PHONE { get; set; }
        public string PATIENT_ADDRESS { get; set; }
        public string PATIENT_AREA { get; set; }
        public string PATIENT_STREET { get; set; }
        public string PATIENT_TYPE { get; set; }
        public string PATIENT_CLINICAL { get; set; }
        public string PATIENT_BQ { get; set; }
        public string PATIENT_IN_TIME { get; set; }
        public string PATIENT_IN_PLACE { get; set; }
        public string PATIENT_SITE { get; set; }
        public string PATIENT_HOUSE_NO { get; set; }
        public string PATIENT_BED_NO { get; set; }
        public string PATIENT_STATUS_NAME { get; set; }
        public string PATIENT_OUT_TIME { get; set; }
        public string PATIENT_OUT_PLACE { get; set; }
        public string PATIENT_LAST_TIME { get; set; }
        public string SURPLUS_TIME { get; set; }
        public string FIRST_TEST_TIME { get; set; }
        public string FIRST_TEST_RESULT_NAME { get; set; }
        public string SECOND_TEST_TIME { get; set; }
        public string SECOND_TEST_RESULT_NAME { get; set; }
        public string IN_REMARK { get; set; }
        public string OUT_REMARK { get; set; }
        public string OUT_REASON { get; set; }
    }
    public enum PROCESS_RESULT
    {
        待审核 = 0,
        审核通过 = 1,
        审核未通过 = 2
    }

}